package io.github.viscent.mtpattern.ch14.hsha.example;

import io.github.viscent.mtpattern.ch5.tpt.example.AlarmType;
import io.github.viscent.util.Debug;

import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

@SuppressWarnings("all")
public class Client {

    public static void main(String[] args) {
        test();
    }

    private static void test() {
        Debug.info("started.");

        final AlarmMgr alarmMgr = AlarmMgr.getInstance();
        alarmMgr.init();

        final String alarmId = "10000020";
        final String alarmExtraInfo = "name1=test;name2=value2";
        Thread t1;
        int count1 = 10;

        Runnable runnable = () -> {
            Timer timer = new Timer(true);
            TimerTask task = new TimerTask() {
                @Override
                public void run() {
                    alarmMgr.sendAlarm(AlarmType.RESUME, alarmId, alarmExtraInfo);
                    timer.cancel();
                }
            };
            timer.schedule(task, 50);
        };
        final CyclicBarrier cbr = new CyclicBarrier(count1, runnable);

        for (int i = 0; i < count1; i++) {
            t1 = new Thread(() -> {
                try {
                    cbr.await();
                } catch (InterruptedException e) {

                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
                for (int j = 0; j < 10; j++) {
                    alarmMgr.sendAlarm(AlarmType.FAULT, alarmId, alarmExtraInfo);
                }
            });
            t1.start();
        }
        Random rnd = new Random();
        Timer timer1 = new Timer(true);
        timer1.schedule(new TimerTask() {
            @Override
            public void run() {
                new Thread(() -> {
                    for (int i = 0; i < 20; i++) {
                        alarmMgr.sendAlarm(AlarmType.FAULT, alarmId, alarmExtraInfo);
                    }
                }).start();
            }
        }, rnd.nextInt(150));

        timer1.schedule(new TimerTask() {
            @Override
            public void run() {
                alarmMgr.shutdown();
            }

        }, 5000);
    }

}
